<?php

namespace Biz\service\activity\project;

use Biz\model\activity\BizProjectGroupModel;
use Biz\model\activity\BizProjectResponsibilityModel;
use Biz\service\admin\tools\SimplePageTpl;
use Biz\service\admin\tools\SimpleRouteTpl;
use Encore\Admin\Facades\Admin;
use Exception;

abstract class BizProjectPageTpl extends SimplePageTpl
{
    use FieldChangeTrait;
    use FieldAuthorizationTrait;

    public static function getRoute(): SimpleRouteTpl
    {
        $fileName = str_replace(BizProjectParseTpl::CLASS_PREFIX, '', static::class);
        return BizProjectParseTpl::getRoute(lcfirst($fileName));
    }

    public static function findAuthModuleIds($adminId, $module = BizProjectResponsibilityModel::RESPONSIBILITY_MODULE_PROJECT): array
    {
        $authAdminId = BizProjectGroupModel::getAuthAdminIdByAdminId($adminId);
        $authAdminId = self::uniqueFilter($authAdminId);
        BizProjectResponsibilityModel::findProjectByAdmin($authAdminId, $module);
        return BizProjectResponsibilityModel::afterFindProject();
    }

    public function put($input, $id)
    {
        // TODO: Implement put() method.
    }

    public function sort($input)
    {

    }

    public function adminId()
    {
        return Admin::user()->username;
    }

    public function isAdmin(): bool
    {
        return in_array($this->adminId(), BizProjectGroupModel::getAdminId());
    }

    /**
     * @throws Exception
     */
    public function adminAuthorError($id = 0)
    {
        if (!$this->isAdmin()) throw new Exception("仅管理员可操作");
    }

    public function getLeaderEmail($responsible, $cc = true): array
    {
        $rs = BizProjectGroupModel::getResponsibleLeader($responsible);
        return $this->formatCcEmail($rs, $cc);
    }

    public function formatCcEmail($rs, $format = true): array
    {
        $cc = [];
        $email = [];
        foreach ($rs as $v) {
            $cc[] = [
                'name' => $v['admin_id'],
                'address' => $v['email'],
            ];
            $email[] = $v['email'];
        }
        return $format ? $cc : $email;
    }

    public function getLeaderEmailByUser($user, $cc = true): array
    {
        $rs = BizProjectGroupModel::getLeaderIdByAdminId($user);
        /**
         *  [
        'name' => 'yanmuxi',
        'address' => 'yanmuxi@haohaozhu.com',
        ],
         */
        return $this->formatCcEmail($rs, $cc);
    }

    public function userButton($href, $icon, $title)
    {
        return <<<EOT

<div class="btn-group pull-right" style="margin-right: 10px">
    <a href="{$href}" target="_blank" class="btn btn-sm btn-success">
        <i class="fa {$icon}"></i>&nbsp;&nbsp;{$title}
    </a>
</div>

EOT;
    }
}